﻿using System.Linq;
using System.Net;
using RpcClient;
using RpcHelper;
using RpcModel;
using Wedonek.RpcStore.Gateway.Interface;
using Wedonek.RpcStore.Gateway.Model;
using Wedonek.RpcStore.Service.Interface;
using Wedonek.RpcStore.Service.Model;

namespace Wedonek.RpcStore.Gateway.Service
{
    internal class IpBlackService : IIpBlackService
    {
        private readonly IIpBlackCollect _IpBlack;
        private readonly IServerTypeCollect _ServerType;
        public IpBlackService(IIpBlackCollect ipBlack,
            IServerTypeCollect serverType)
        {
            this._ServerType = serverType;
            this._IpBlack = ipBlack;
        }
        public int Add(AddIpBlackParam add)
        {
            return this._IpBlack.Add(add.ConvertMap<AddIpBlackParam, AddIpBlack>((a, b) => {
                b.Ip = IPAddress.Parse(a.IpAddress).Address;
                if(a.EndIpAddress!= null)
                {
                    b.EndIp = IPAddress.Parse(a.EndIpAddress).Address;
                }
                return b;
            }));
        }

        public void Drop(int id)
        {
            IpBlackDatum black = this._IpBlack.Get(id);
            this._IpBlack.Drop(black);
        }

        public IpBlackDatum Get(int id)
        {
            return this._IpBlack.Get(id);
        }

        public IpBlack[] Query(IpBlackQuery query, IBasicPage paging, out long count)
        {
            IpBlackDatum[] list = this._IpBlack.Query(query, paging, out count);
            if (list.Length == 0)
            {
                return null;
            }
            ServerType[] types = this._ServerType.Gets(list.Distinct(a => a.SystemType));
            return list.ConvertMap<IpBlackDatum, IpBlack>((a, b) =>
            {
                b.TypeName = types.Find(c => c.TypeVal == a.SystemType, c => c.SystemName);
                return b;
            });
        }

        public int Set(int id, SetIpBlackParam set)
        {
            IpBlackDatum black = this._IpBlack.Get(id);
            return this._IpBlack.Set(black, set.ConvertMap<SetIpBlackParam, SetIpBlack>((a, b) => {
                b.Ip = IPAddress.Parse(a.IpAddress).Address;
                if (a.EndIpAddress != null)
                {
                    b.EndIp = IPAddress.Parse(a.EndIpAddress).Address;
                }
                return b;
            }));
        }

        public void SetRemark(int id, string remark)
        {
            IpBlackDatum black = this._IpBlack.Get(id);
            this._IpBlack.SetRemark(black, remark);
        }
    }
}
